﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace HJ212_Common
{
    public class StreamAndBytes
    {
        /* - - - - - - - - - - - - - - - - - - - - - - - - 
         * Stream 和 byte[] 之间的转换 
         * - - - - - - - - - - - - - - - - - - - - - - - */

        /// <summary> 
        /// 将 Stream 转成 byte[] 
        /// </summary> 
        public static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
        /// <summary> 
        /// 将 byte[] 转成 Stream 
        /// </summary> 
        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }

        /// <summary> 
        /// 将 string 转成 byte[] 
        /// </summary> 
        public static byte[] stringToBytes(string str)
        {
            byte[] byts = Encoding.UTF8.GetBytes(str);
            return byts;
        }


        /// <summary> 
        /// 将 string 转成 Stream 
        /// </summary> 
        public static Stream stringToStream(string str)
        {
            byte[] bytes = stringToBytes(str);
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
        /// <summary> 
        ///  
        /// </summary> 
        /* - - - - - - - - - - - - - - - - - - - - - - - - 
        * Stream 和 文件之间的转换 
        * - - - - - - - - - - - - - - - - - - - - - - - */
        /// <summary>
        /// 将 Stream 写入文件
        /// </summary>
        /// <param name="stream">传入的Stream流对象</param>
        /// <param name="fileName">要存储的完整路径文件名</param>
        /// <param name="fileSize">文件大小</param>
        public static void StreamToFile(Stream stream, string fileName, out int fileSize)
        {
            FileStream fs, targetStream;

            //文件流传输
            using (targetStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                //定义文件缓冲区
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;

                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
                fileSize = (int)targetStream.Length;
                targetStream.Close();
                stream.Close();
            }
        }


        /* - - - - - - - - - - - - - - - - - - - - - - - - 
        * Stream 和 文件之间的转换 
        * - - - - - - - - - - - - - - - - - - - - - - - */
        /// <summary>
        /// 将 string 写入文件
        /// </summary>
        /// <param name="str">传入的string对象</param>
        /// <param name="fileName">要存储的完整路径文件名</param>
        /// <param name="fileSize">文件大小</param>
        public static void StringToFile(string str, string fileName, out int fileSize)
        {

            string filePath = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            using (StreamWriter writer = File.AppendText(fileName))
            {
                writer.WriteLine(str);
                writer.Flush();
                fileSize = (int)writer.BaseStream.Length;
                writer.Close();
            }

        }

        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="fileName">要存储的完整路径文件名</param>
        public static string ReadFromFile(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            string str = string.Empty;
            using (StreamReader reader = File.OpenText(fileName))
            {
                while ((str = reader.ReadLine()) != null)
                {
                    sb.Append(str);
                }
                reader.Close();
                return sb.ToString();
            }
        }
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="fileName">要存储的完整路径文件名</param>
        public static List<string> ReadLstFromFile(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            string str = string.Empty;
            List<String> lst = new List<string>();
            using (StreamReader reader = File.OpenText(fileName))
            {
                while ((str = reader.ReadLine()) != null)
                {
                    lst.Add(str);
                }
                reader.Close();
                return lst;
            }
        }
        /// <summary>
        /// 读取文件内容,每行用分隔符隔开
        /// </summary>
        /// <param name="fileName">要存储的完整路径文件名</param>
        /// <param name="splitWord">要分割的分隔符</param>
        public static string ReadFromFile(string fileName, char splitWord)
        {
            StringBuilder sb = new StringBuilder();
            string str = string.Empty;
            using (StreamReader reader = File.OpenText(fileName))
            {
                while ((str = reader.ReadLine()) != null)
                {
                    sb.Append(splitWord + str);
                }
                reader.Close();
                return sb.ToString();
            }
        }
        /// <summary> 
        /// 从文件读取 Stream 
        /// </summary> 
        public static Stream FileToStream(string fileName)
        {

            string filePath = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            // 打开文件 
            Stream stream = null;
            try
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                // 读取文件的 byte[] 
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();
                // 把 byte[] 转换成 Stream 
                stream = new MemoryStream(bytes);
            }
            catch (Exception Ex)
            {
                return null;

            }

            return stream;


        }

        /// <summary> 
        /// 从文件读取 byte[] 
        /// </summary> 
        public static byte[] FileToBytes(string fileName)
        {
            try
            {
                return StreamToBytes(FileToStream(fileName));
            }
            catch (Exception Ex)
            {
                return null;

            }

        }


        /// <summary>
        ///  File 输出
        /// </summary>
        /// <param name="serverPath">服务器文件路径</param>
        /// <param name="localPath"> 本地路径   c:\ 桌面 </param>
        public static void OutputFile(string serverPath, string localPath, string FileName)
        {
            WebClient webClient = null;
            System.IO.FileStream fileStream = null;
            string createDirectory = string.Empty;
            string newDirectory = string.Empty;
            try
            {

                webClient = new WebClient();   //需要用到 WebClient
                byte[] buffer = webClient.DownloadData(serverPath);
                if (0 < buffer.Length)
                {
                    //如果 不存在，创建
                    if (!Directory.Exists(localPath))
                    {
                        Directory.CreateDirectory(localPath);
                    }
                    //创建成功
                    fileStream = new System.IO.FileStream(localPath + FileName,
                    System.IO.FileMode.Create,
                    System.IO.FileAccess.Write,
                    System.IO.FileShare.None
                    );
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileStream.Flush();
                }

            }

            catch (Exception ex)
            {
                throw;
            }

            finally
            {
                if (null != fileStream)
                {
                    fileStream.Close();
                }
            }

        }

        //#endregion



    }
}
